package io.renren.modules.lucky.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.sms.AliyunSms;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.lucky.dao.AppUserSmsDao;
import io.renren.modules.lucky.entity.AppUserSmsEntity;
import io.renren.modules.lucky.service.AppUserSmsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("appUserSmsService")
public class AppUserSmsServiceImpl extends ServiceImpl<AppUserSmsDao, AppUserSmsEntity> implements AppUserSmsService {

    @Autowired
    private AppUserSmsDao appUserSmsDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppUserSmsEntity> page = this.page(
                new Query<AppUserSmsEntity>().getPage(params), new QueryWrapper<AppUserSmsEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional(readOnly = false)
    public Map<String, Object> validCode(String phoneNum) throws ClientException {
        Map<String, Object> map = new HashMap<String, Object>();
        // 手机号是否正确
        if (StringUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
            map.put("ret", "5");
            map.put("info", "不是合法的手机号码");
            return map;
        }
        // 检查验证码
        Map<String, String> check = checkCodeSend(phoneNum);
        if (!check.get("boo").equals("true")) {
            map.putAll(check);
            return map;
        }
        // 发短信验证码
        String checkCode = "";
        if (StringConstants.isdebug) {
            checkCode = "1234";
        } else {
            checkCode = AliyunSms.sendSmsBackCode(phoneNum);
            if (checkCode.equals("0000")) {
                map.put("ret", "6");
                map.put("info", "短信发送失败");
                return map;
            }
        }
        // 设置该号码下所有登陆验证码失效
        AppUserSmsEntity smsEntity = new AppUserSmsEntity();
        smsEntity.setSmsFlag(0);
        baseMapper.update(smsEntity, new QueryWrapper<AppUserSmsEntity>().eq("phone_num", phoneNum).eq("sms_flag", "1"));
        // 插入一条新的验证码
        Date date = new Date();
        smsEntity.setSmsCode(checkCode);
        smsEntity.setCreateTime(date);
        smsEntity.setPhoneNum(phoneNum);
        smsEntity.setSmsFlag(1);
        smsEntity.setUpdateTime(date);
        boolean boo = retBool(baseMapper.insert(smsEntity));
        if (boo) {
            map.put("ret", "1");
            map.put("info", "成功获取验证码");
            map.put("sms_code", checkCode);
            return map;
        } else {
            map.put("ret", "2");
            map.put("info", "数据插入失败！请稍候再试");
            return map;
        }
    }

    private Map<String, String> checkCodeSend(String phoneNum) {
        Map<String, String> map = new HashMap<String, String>();
        //1、取出验证码信息
        AppUserSmsEntity smsEntity = baseMapper.selectOne(new QueryWrapper<AppUserSmsEntity>().eq("sms_flag", 1)
                .eq("phone_num", phoneNum).orderByDesc("create_time"));
        if (smsEntity == null) {
            map.put("boo", "true");
            return map;
        }
        long now = new Date().getTime();
        if (smsEntity.getCreateTime() != null) {
            long itime = now - smsEntity.getCreateTime().getTime();
            // 判断短信再次请求时间 60s
            if (itime < StringConstants.sendSmsTime) {
                map.put("boo", "false");
                map.put("ret", "3");
                map.put("info", "验证码频繁请求！稍候再试");
                return map;
            }
            // 判断短信的有效时间 5分钟
            if (itime < StringConstants.validSmsTime && itime > StringConstants.sendSmsTime) {
                map.put("boo", "false");
                map.put("ret", "4");
                map.put("info", "验证码五分钟有效！请登录");
                return map;
            }
        }
        map.put("boo", "true");
        return map;
    }

    @Override
    public Map<String, Object> validPhoneWithSmscode(String phoneNum, String smsCode) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 手机号是否正确
        if (StringUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
            map.put("ret", "2");
            map.put("info", "不是合法的手机号码");
            return map;
        }

        // 验证码是否正确
        AppUserSmsEntity smsEntity = appUserSmsDao.selectOne(new QueryWrapper<AppUserSmsEntity>()
                .eq("phone_num", phoneNum).eq("sms_code", smsCode).eq("sms_flag", 1));
//        map.clear();
        if (smsEntity == null) {
            map.put("ret", "3");
            map.put("info", "验证码不正确");
            return map;
        }

        // 设置该号码下所有登陆验证码失效
        smsEntity = new AppUserSmsEntity();
        smsEntity.setSmsFlag(0);
        appUserSmsDao.update(smsEntity, new QueryWrapper<AppUserSmsEntity>().eq("phone_num", phoneNum)
                .eq("sms_code", smsCode));
        return map;
    }

}